package com.zhj.micro.product.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.zhj.micro.product.MicroProductApplication;
import com.zhj.micro.product.entity.Order;
import com.zhj.micro.product.entity.ProductStorage;
import com.zhj.micro.product.mapper.ProductStorageMapper;
import com.zhj.micro.product.service.ProductStorageService;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ProductStorageServiceImpl implements ProductStorageService {

    @Resource
    private ProductStorageMapper productStorageMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public int insert(ProductStorage record) {
        return productStorageMapper.insert(record);
    }

    @Override
    public void processOrder(Order order) throws JsonProcessingException {
        Long productId = order.getProductId();
        Long num = order.getNum();
        //扣减库存
        boolean result = productStorageMapper.freezeStorage(productId, num);
        if (result) {
            //发送库存处理完成的消息，处理订单的状态为已出库
            order.setOrderStatus((byte) 3);
            this.rabbitTemplate.convertAndSend("order_product_exchange", "order.product",
                                               MicroProductApplication.OBJECT_MAPPER.writeValueAsString(order));
        }
    }

}
